package com.motu.monstercity.server.game.logic;

import com.hazelcast.core.LifecycleService;
import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.protocol.CsGameFeast.CSGameFeastPushDataResponse;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.feast.FeastConstant;
import com.motu.monstercity.server.game.commondata.feast.FeastCreaterReward;
import com.motu.monstercity.server.game.commondata.feast.FeastJoin;
import com.motu.monstercity.server.game.commondata.feast.FeastMain;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.skill.SkillConstant;
import com.motu.monstercity.server.game.commondata.system.UserExp;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.timedtask.ServerSnatchOfferTask;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class FeastManager extends FeastUserData {
    public final static Logger logger = LoggerFactory.getLogger(FeastManager.class);

    /**
     * 派对完成处理的业务逻辑
     * @param serverFeast
     * createTime 派对的举办时间，普通派对人满会先结束掉
     */
    public static void handleFeastComplete(ServerFeast serverFeast, long createTime) {
        logger.info("### handleFeastComplete serverFeast = " + serverFeast.getUserId() + " feastMainId:" + serverFeast.getFeastMainId() + " addtime:" + serverFeast.getAddTime() + " createtim:" + createTime);
        // 给举办者发放奖励
        FeastMain feastMain = getFeastMain(serverFeast.getFeastMainId());
        if (feastMain == null) {
            return;
        }
        List<RewardItem> rewardItemList = new ArrayList<>();
        if (feastMain.isCommonFeast()) {// 普通派对的奖励= 所有参与者的奖励总和
            if (createTime != serverFeast.getAddTime()) {// 人满提前结束，已经发放过奖励了，这是新举办的一场
                logger.info("###handleFeastComplete full serverFeast = " + serverFeast.getUserId() + " createTime:" + createTime);
                return;
            }

            int guestNum = serverFeast.getGuestNum();// 当前参与的数量
            // 添加机器人
            int robotNum = AllParam.FEAST_JOIN_ROBOT_MAX_NUM - guestNum;
            long curTime = TimeUtils.getCurTime();
            UserInfo userInfo = GameUser.getUserInfo(serverFeast.getUserId());
            FeastJoin robotJoin = getRobotJoin();// 机器人的参加类型
            for (int i=0; i<robotNum; i++) {
                long robotAddTime = curTime - TimeUtils.HOUR * (i);// 机器人的加入时间
                handleJoinFeast(serverFeast, userInfo, robotJoin, robotAddTime, true);// 生成参与数据
            }

            List<ServerFeastSeat> seatList = getServerFeastSeatList(serverFeast.getId());// 参与列表
            for (ServerFeastSeat serverFeastSeat : seatList) {
                int joinTypeId = serverFeastSeat.getJoinId();// 赞助类型
                FeastJoin feastJoin = getFeastJoin(joinTypeId);
                if (feastJoin != null) {
                    CommonUtils.mergeItemList(rewardItemList, CommonUtils.takeReawrdItemFromStr(feastJoin.getReward()));
                }
            }
        } else if (feastMain.isCelebFeast()) {// 盛典派对的奖励根据参与者人数来定
            FeastCreaterReward feastCreaterReward = getFeastCreaterReward(serverFeast.getGuestNum());
            if (feastCreaterReward != null) {
                rewardItemList = CommonUtils.takeReawrdItemFromStr(feastCreaterReward.getReward());
            }
        }
        if (rewardItemList.size() > 0) {
            countFeastCreateReward(serverFeast.getUserId(), rewardItemList);// 派对结束后，举办者获得的实际奖励，技能会增加人气
            if (serverFeast.getIsThree() == 1) {// 三倍奖励
                CommonUtils.multipleItemList(rewardItemList, AllParam.FEAST_THREE_REWARD);
            }
            MailManager.sendSystemMail(serverFeast.getUserId(), MailConstant.FEAST_COMPLETE_REWARD_TITLE, MailConstant.FEAST_COMPLETE_REWARD_CONTENT, rewardItemList, LogType.FEAST_CREATE);
        }

        // 生成派对的举办记录
        UserFeastRecord userFeastRecord = new UserFeastRecord(serverFeast);
        userFeastRecord.doCreate();

        List<ServerFeastSeat> seatList = getServerFeastSeatList(serverFeast.getId());
        for (ServerFeastSeat entity : seatList) {
            entity.delete();//删除座位信息
        }

        FeastManager.publicFeastToCreater(serverFeast);// 给举办推送派对已经人满，结束
        serverFeast.delete();// 删除派对
    }

    // 参加派对， 增加派对的参与人数，生成派对座位信息serverFeastSeat，生成派对的参与详情user_feast_join_detail
    public static void handleJoinFeast(ServerFeast serverFeast, UserInfo userInfo, FeastJoin feastJoin, long addTime, boolean isRobot) {
        serverFeast.addGuestNum(1);
        serverFeast.putJoinTime(addTime);

        int position = serverFeast.getGuestNum();// 参与者的座位编号从1开始
        int joinId = feastJoin == null ? 0 : feastJoin.getId();
        ServerFeastSeat serverFeastSeat = new ServerFeastSeat(serverFeast.getId(), userInfo, position, joinId, addTime, isRobot);
        serverFeastSeat.doCreate();

        if (serverFeast.isCommonFeast()) {// 普通派对生成参与详情
            UserFeastJoinDetail userFeastJoinDetail = new UserFeastJoinDetail(serverFeast.getId(), userInfo, joinId, isRobot);
            userFeastJoinDetail.doCreate();

            serverFeast.addScore(feastJoin.takeFeastScore());// 普通派对
        } else {
            serverFeast.putScore(serverFeast.countCelebScore());// 盛典派对
        }
    }

    // userid 和feastmain 的id 组成唯一值。同个派对，一个玩家只能同时举办一个feastMainId + userid 的后面10位
    public static String getFeastUniqKey(long userId, int feastMainId) {
        return userId + "_" + feastMainId;
    }

    // 生成机器人的userid，999999 开头，后面的xx 表示位置，避免重复
    public static long getRobotUserId(int position) {
        long aa = 999999L * 100;
        return aa + position;
    }

    // 参加盛典派对的奖励
    public static List<RewardItem> getCelebJoinReward(ServerFeast serverFeast) {
        if (serverFeast == null || serverFeast.getGuestNum() == 0) {
            return null;
        }
        FeastJoin feastJoin = getFeastJoin(FeastConstant.FEAST_TYPE_2, 2);// 50名后面的参加奖励
        if (serverFeast.getGuestNum() <= AllParam.FEAST_CELEB_JOIN_REWARD_MIN_NUM) {
            feastJoin = getFeastJoin(FeastConstant.FEAST_TYPE_2, 1);// 前面50名的参加奖励
        }
        return CommonUtils.takeReawrdItemFromStr(feastJoin.getReward());
    }

    /**
     * 参加别人的派对，我获得的奖励
     * @param serverFeast
     * @return
     */
    public static List<RewardItem> countFeastJoinReward(UserInfo userInfo, ServerFeast serverFeast, FeastJoin feastJoin) {
        FeastMain feastMain = FeastManager.getFeastMain(serverFeast.getFeastMainId());
        List<RewardItem> rewardItemList = feastMain.isCelebFeast() ? getCelebJoinReward(serverFeast) : CommonUtils.takeReawrdItemFromStr(feastJoin.getReward());
        int skillAdd = SkillManager.getSkillMoudleAdd(userInfo.getId(), SkillConstant.EFFECT_TYPE_34, 0);// 参加别人的派对，参与者的人气增加百分比
        UserExp userExp = GameDataManager.getUserExp(userInfo.getLevel());
        int cityAdd = userExp == null ? 0 : userExp.getFeastEffect();// 城市等级也有加成
        for (RewardItem rewardItem : rewardItemList) {
            if (rewardItem.getItemId() == ItemId.FEAST_SCORE) {
                long newNum = CommonUtils.countPerValue(rewardItem.getItemNum(), skillAdd + cityAdd);
                rewardItem.setItemNum(newNum);
            }
        }
        return rewardItemList;
    }

    /**
     * 派对结束后，举办者获得的实际奖励，技能会增加人气
     * @param userId
     * @param rewardItemList
     * @return
     */
    public static void countFeastCreateReward(long userId, List<RewardItem> rewardItemList) {
        int skillAdd = SkillManager.getSkillMoudleAdd(userId, SkillConstant.EFFECT_TYPE_33, 0);// 举办派对，派对结束后人气提升@
        if (skillAdd > 0) {
            for (RewardItem rewardItem : rewardItemList) {
                if (rewardItem.getItemId() == ItemId.FEAST_SCORE) {
                    long newNum = CommonUtils.countPerValue(rewardItem.getItemNum(), skillAdd);
                    rewardItem.setItemNum(newNum);
                }
            }
        }
    }

    /**
     * 给本服所有玩家进行广播, 通知有盛典派对举办
     * @param userInfo
     * @param serverFeast
     */
    public static void publicFeastAllUser(UserInfo userInfo, ServerFeast serverFeast) {
        CSGameFeastPushDataResponse.Builder builder = CSGameFeastPushDataResponse.newBuilder();
        builder.setFeast(serverFeast.takeInitBuilder());
        JsonObject jsonObject = ResponseUtils.getFeastResponseData(builder.build().toByteArray());
        JsonArray serverIdList = new JsonArray().add(userInfo.getServerId());
        BoardcastManager.publicAllUser(serverIdList, userInfo.getId(), jsonObject);
    }

    // 普通派对人满结束时。给举办者推送通知
    public static void publicFeastToCreater(ServerFeast serverFeast) {
        CSGameFeastPushDataResponse.Builder builder = CSGameFeastPushDataResponse.newBuilder();
        builder.setFeast(serverFeast.takeInitBuilder());
        JsonObject jsonObject = ResponseUtils.getFeastResponseData(builder.build().toByteArray());
        GameUser.pushToUser(serverFeast.getUserId(), jsonObject);
    }
}
